package vamp_serviceweb

import org.springframework.dao.DataIntegrityViolationException

class POIController {

    def geocoderService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [POIInstanceList: POI.list(params), POIInstanceTotal: POI.count()]
    }

    def create() {
        [POIInstance: new POI(params)]
    }

    def save() {
        def POIInstance = new POI(params)

        //Creation et ajout d'une adresse
        def adresseInstance = new Address(line1:  params.line1, line2 : params.line2, line3: params.line3, zipCode: params.zipCode, city: params.city, country: params.country)
        String addr = params.line1+" "+params.line2+" "+params.line3+" "+params.zipCode+" "+params.city+" "+params.country
        println("Adresse : "+addr)
        //Récupération des coordonnée GPS via googlemap
        def result = geocoderService.reverseGeocode(addr)
        //result ==> result.lat et result.lng
        println "Latitude: ${result.lat}"
        println  "Longitude: ${result.lng}"
        def gpsLocationInstance = new GPSLocation(latitude: result.lat, longitude: result.lng)
        adresseInstance.gpsLocation = gpsLocationInstance
        POIInstance.addresse = adresseInstance


        //creation d'un link avec upload de fichier
        def uploadedFile = request.getFile('payload')
        if(!uploadedFile.empty){
            println "Class: ${uploadedFile.class}"
            println "Name: ${uploadedFile.name}"
            println "OriginalFileName: ${uploadedFile.originalFilename}"
            println "Size: ${uploadedFile.size}"
            println "ContentType: ${uploadedFile.contentType}"
            def webRootDir = servletContext.getRealPath("/")
            def userDir = new File(webRootDir, "/payload/${entryInstance.author.login}")
            userDir.mkdirs()
            uploadedFile.transferTo(new File(userDir, uploadedFile.originalFilename))
            def linkInstance = new Link(filename: uploadedFile.originalFilename)
            linkInstance.poi = POIInstance
            POIInstance.links.add(linkInstance)
        }


        if (!POIInstance.save(flush: true)) {
            render(view: "create", model: [POIInstance: POIInstance])
            return
        }


        flash.message = message(code: 'default.created.message', args: [message(code: 'POI.label', default: 'POI'), POIInstance.id])
        redirect(action: "show", id: POIInstance.id)
    }

    def show() {
        def POIInstance = POI.get(params.id)
        if (!POIInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'POI.label', default: 'POI'), params.id])
            redirect(action: "list")
            return
        }

        [POIInstance: POIInstance]
    }

    def edit() {
        def POIInstance = POI.get(params.id)
        if (!POIInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'POI.label', default: 'POI'), params.id])
            redirect(action: "list")
            return
        }

        [POIInstance: POIInstance]
    }

    def update() {
        def POIInstance = POI.get(params.id)
        if (!POIInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'POI.label', default: 'POI'), params.id])
            redirect(action: "list")
            return
        }

        if (params.version) {
            def version = params.version.toLong()
            if (POIInstance.version > version) {
                POIInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'POI.label', default: 'POI')] as Object[],
                        "Another user has updated this POI while you were editing")
                render(view: "edit", model: [POIInstance: POIInstance])
                return
            }
        }

        POIInstance.properties = params

        if (!POIInstance.save(flush: true)) {
            render(view: "edit", model: [POIInstance: POIInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'POI.label', default: 'POI'), POIInstance.id])
        redirect(action: "show", id: POIInstance.id)
    }

    def delete() {
        def POIInstance = POI.get(params.id)
        if (!POIInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'POI.label', default: 'POI'), params.id])
            redirect(action: "list")
            return
        }

        try {
            POIInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'POI.label', default: 'POI'), params.id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'POI.label', default: 'POI'), params.id])
            redirect(action: "show", id: params.id)
        }
    }
}
